package com.mycity.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.impl.client.DefaultBackoffStrategy;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.mycity.bean.Post;
import com.mycity.bean.User;
import com.mycity.mapper.PostRowMapper;
import com.mysql.jdbc.PreparedStatement;


public class PostDao extends RDSDao{

	public List<Post> retrievePostsByUserId(int userId) {
		Object params[] = { userId };
	    List<Post> posts = this.getTemplate().query("SELECT * from Post where userId=?", params, new PostRowMapper());   	    
    
	    return posts;
	}
	
	public Post getPost(int postId) {
		Object params[] = { postId };
	    List<Post> posts = this.getTemplate().query("SELECT * from Post where postId=?", params, new PostRowMapper());   	    
    
	    return posts.get(0);
	}

	public int writePost(final int userId, final int postType, final String postContent, final String postDate){
		final String insertSQL = "INSERT INTO Post(postType, postContent, postDate, userId) VALUES(?,?,?,?)";
	   
	    KeyHolder holder = new GeneratedKeyHolder();

	    this.getTemplate().update(new PreparedStatementCreator() {           


						@Override
						public java.sql.PreparedStatement createPreparedStatement(
								Connection con) throws SQLException {
	                        PreparedStatement ps = (PreparedStatement) con.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
	                        ps.setInt(1, postType);
	                        ps.setString(2, postContent);
	                        ps.setString(3, postDate);
	                        ps.setInt(4, userId);
	                        return ps;
						}
	                }, holder);

	    int postId = holder.getKey().intValue();
	    
	    return postId;
	}
	
	public List<Post> recentPosts(){
		List<Post> posts = this.getTemplate().query("SELECT * FROM Post ORDER BY postDate ASC LIMIT 20",new PostRowMapper());
		return posts;
	}
}
